#include "freqgainucs.h"
#include "dm/dmdef.h"
#include "dm/filter.h"

#include <algorithm>


FreqGainUCS::FreqGainUCS(QWidget *parent)
    : AWidget{parent}
{
    m_offset = 28 * ratio();
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    curve = new FreqGainCurve(this);

    connect(curve, &FreqGainCurve::stateChanged, this, &FreqGainUCS::stateChanged);
}

void FreqGainUCS::setList(const QList<DMVariant> &list)
{
    curve->setList(list);
}

void FreqGainUCS::updateDm(const int &index, const DMVariant &dm)
{
    curve->updateCtrl(index, dm);
}

void FreqGainUCS::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    auto pen = painter.pen();

    pen.setColor(Qt::gray);
    painter.setPen(pen);

    const double w = width() - 1;
    const double h = height() - 1;

    // 坐标系实际大小
    const double aw = w - m_offset * 2;
    const double ah = h - m_offset * 2;

    m_cRect = QRect(m_offset, m_offset, aw, ah);

    const auto oy = m_cRect.bottomLeft().y();
    const auto ox = m_cRect.bottomLeft().x();

    // 坐标系框
    pen.setWidth(1);
    pen.setColor(QColor(94, 99, 107));
    painter.setPen(pen);
    // 网格线
    // y轴
    for (int gain = EQ_GAIN_MIN; gain <= EQ_GAIN_MAX; gain += EQ_GAIN_LABEL_STEP / 2) {
        auto p1 = toPoint(m_cRect, EQ_FREQUENCY_MIN, gain);
        auto p2 = toPoint(m_cRect, EQ_FREQUENCY_MAX, gain);
        painter.drawLine(p1, p2);
        if (0 == gain % EQ_GAIN_LABEL_STEP) {
            auto str = QString::number(gain);
            if (0 == gain) {
                str += LABEL_DECIBEL_UINT;
            }
            painter.drawText(QRectF(ox - m_offset, p1.y() - m_offset, m_offset - 5 * ratio(), m_offset * 2), Qt::AlignVCenter | Qt::AlignRight, str);
        }
    }
    // x轴
    for (size_t i = 0; i < EQ_FREQUENCY_AUX.size(); ++i) {
        auto aux = EQ_FREQUENCY_AUX.at(i);
        auto p1 = toPoint(m_cRect, EQ_FREQUENCY_AUX.at(i), EQ_GAIN_MAX);
        auto p2 = toPoint(m_cRect, EQ_FREQUENCY_AUX.at(i), EQ_GAIN_MIN);
        painter.drawLine(p1, p2);
        if (std::find(EQ_FREQUENCY_LABEL.begin(), EQ_FREQUENCY_LABEL.end(), aux) != EQ_FREQUENCY_LABEL.end()) {
            QString str;
            if (aux < 1000) {
                str = QString::number(aux);
            }
            else {
                str = QString::number(aux / 1000) + "K";
            }
            painter.drawText(QRectF(p1.x() - m_offset / 2, oy + 5 * ratio(), m_offset, m_offset), Qt::AlignHCenter, str);
        }
    }
    curve->setGeometry(m_cRect);
}

QPointF FreqGainUCS::toPoint(const QRectF &rect, const double &freq, const double &gain) const
{
    return QPointF(rect.x() + rect.width() * Filter::freqToWidth(freq), rect.y() + rect.height() * Filter::gainToHeight(gain));
}
